
import socket
import threading
import time
import logging

logger = logging.getLogger('tcp_client')


def tcp_client_thread(client_socket, ip_address, port):

    """TCP客户端线程函数"""
    conmand = b"\x01\x03\x00\x00\x00\x04\x44\x09"
    try:
        while True:
            if not is_socket_connected(client_socket):
                client_socket.connect((ip_address, port))
                time.sleep(1)
                continue

            client_socket.send(conmand)
            data = client_socket.recv(1024)
            if not data:
                continue
            print(f"Received: {data}")
            print(f"湿度{int(data[3:5].hex(), base=16) / 10}, 温度{int(data[5:7].hex(), base=16) / 10}")

            time.sleep(1)

            # client_socket.sendall(data)  # 回显数据
    except TimeoutError:
        print("超时")
    except ConnectionResetError:
        print("Client disconnected")
    finally:
        client_socket.close()

def is_socket_connected(sock):
    try:
        # 发送一个空字节，这不会改变连接状态
        # sock.settimeout(0.1)
        sock.send(b'')
        return True
    except (socket.error, ConnectionResetError, socket.timeout):
        return False



def main():
    try:
        ip_address = "192.168.0.66"
        ports = [9001, 9001, 9001]
        clients = []


        for port in ports:
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            client_socket.connect((ip_address, port))
            client_socket.settimeout(3)
            thread = threading.Thread(target=tcp_client_thread, kwargs={'client_socket': client_socket, 'ip_address': ip_address, 'port': port})

            thread.daemon = True

            thread.start()
            clients.append(client_socket)

        
        # 主循环
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        # 停止所有线程
        for client in clients:
            client.close()


        logger.info("收到中断信号，关闭所有客户端连接")

    except Exception as e:
        #logger.error(f"服务器错误: {str(e)}")
        logger.error("服务器错误: {}".format(
            str(e)
        ))


if __name__ == '__main__':
    main()